package com.uduew.sjd.ui.login

import android.os.Bundle
import com.uduew.sjd.BR
import com.uduew.sjd.R
import com.uduew.sjd.bean.CustomerBean
import com.uduew.sjd.bean.HttpBean
import com.uduew.sjd.bean.LoginBean
import com.uduew.sjd.config.AppConfig
import com.uduew.sjd.config.Const
import com.uduew.sjd.message.Messages
import com.uduew.sjd.message.PageMessenger
import com.uduew.sjd.net.DataResult
import com.uduew.sjd.request.LoginRequester
import com.uduew.sjd.request.PenileRequester
import com.uduew.sjd.ui.base.BaseActivity
import com.uduew.sjd.ui.base.StateHolder
import com.uduew.sjd.utils.ResUtil
import com.uduew.sjd.utils.StatusBarUtil
import com.uduew.sjd.utils.ToastUtils
import com.uduew.sjd.utils.Utils
import com.uduew.sjd.view.CodeInputView
import com.uduew.sjd.view.CountDownTextView
import com.uduew.sjd.view.xpop.AcclaimXpop
import com.uduew.sjd.view.xpop.CustomerXpop
import com.kongzue.dialogx.dialogs.PopTip
import com.kongzue.dialogx.dialogs.TipDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kunminx.architecture.ui.page.DataBindingConfig
import com.kunminx.architecture.ui.state.State
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.uduew.sjd.SplashActivity
import com.uduew.sjd.api.AppControlApi
import com.uduew.sjd.bean.IsRegisterBean
import com.uduew.sjd.config.Const.VIDEO_NAME
import com.uduew.sjd.net.DataRepository
import com.uduew.sjd.request.IsRegisterRequester


class LoginActivity : BaseActivity() {

    private lateinit var mStates: LoginActivityStates
    private lateinit var mPenileRequester: PenileRequester
    private lateinit var mLoginRequester: LoginRequester
    private lateinit var mAcclaimXpop: AcclaimXpop
    private lateinit var mCustomerXpop: CustomerXpop
    private lateinit var data: PopupAnimation
    private lateinit var mMessenger: PageMessenger
    private lateinit var mIsRegisterRequester: IsRegisterRequester

    override fun initViewModel() {
        mStates = getActivityScopeViewModel(LoginActivityStates::class.java)
        mPenileRequester = getActivityScopeViewModel(PenileRequester::class.java)
        mLoginRequester = getActivityScopeViewModel(LoginRequester::class.java)
        mIsRegisterRequester = getActivityScopeViewModel(IsRegisterRequester::class.java)
        mMessenger = getApplicationScopeViewModel(PageMessenger::class.java)
        data = PopupAnimation.ScaleAlphaFromCenter
    }

    override fun getDataBindingConfig(): DataBindingConfig? {
        return DataBindingConfig(R.layout.actvity_login, BR.vm, mStates).addBindingParam(
            BR.click,
            ClickProxy()
        ).addBindingParam(BR.listener, CountDownHandler())
            .addBindingParam(BR.codeListener, CodeCompleteHandler())
    }


    override fun onBackPressed() {
        if (mStates.verificationCodeState.get() == 1) {
            mStates.verificationCodeState.set(0)
            mStates.verificationCode.set("")
        } else {
            super.onBackPressed()
        }
    }

    private fun login() {
        mLoginRequester.request(
            this@LoginActivity,
            mStates.loginPhone.get(),
            Const.MINUTEMAN,
            mStates.verificationCode.get(),
            ""
        )
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setStatusBar(this, false, 0, true)
        mPenileRequester.result.observe(this) { dataResult: DataResult<HttpBean<Any>> ->
            WaitDialog.dismiss()
            if (dataResult.responseStatus.isSuccess) {
                mStates.verificationCodeState.set(1)
                AppConfig.loginPhone = mStates.loginPhone.get().toString()
            } else {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
            }
        }

        mIsRegisterRequester.result.observe(this) { dataResult: DataResult<HttpBean<IsRegisterBean>> ->
            if (dataResult.responseStatus.isSuccess) {
                dataResult.result.data.let {
                    if (it != null) {
                        AppConfig.isFirstRegister = it.putrefy
                    }
                }
            }
            login()
        }
        mLoginRequester.result.observe(this) { dataResult: DataResult<LoginBean> ->
            WaitDialog.dismiss()
            if (dataResult.responseStatus.isSuccess) {
                val api = AppControlApi()
                api.setVideoName(VIDEO_NAME)
                DataRepository.getInstance().appControl(
                    this,
                    api
                ) { result: DataResult<HttpBean<Boolean>> ->
                    if (!result.responseStatus.isSuccess) {
                        ToastUtils.showShortToast(result.responseStatus.responseCode)
                        return@appControl
                    }
                    if (result.result.data2 == true) {
                        AppConfig.mConfigs.token().set(dataResult.result.anchylose.deferable)
                        AppConfig.mConfigs.user().set(dataResult.result)
                        AppConfig.mConfigs.phone().set(dataResult.result.anchylose.phone)
                        AppConfig.isLogin = AppConfig.mConfigs.token().get().isNotEmpty()
                        mMessenger.input(Messages(Messages.EVENT_LOGIN_SUCCESS))
                        finish()
                    } else {
                        ToastUtils.showShortToast("request fail")
                    }
                }
            } else {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
            }
        }
    }

    open inner class CodeCompleteHandler : CodeInputView.OnCodeCompleteListener {
        override fun onCodeComplete(code: String?) {
            mStates.verificationCode.set(code.toString())
        }
    }

    open inner class CountDownHandler : CountDownTextView.OnCountDownListener {
        override fun onClick(view: CountDownTextView?) {
            sendCode()
        }

        override fun onTick(view: CountDownTextView?, millisUntilFinished: Long) {

        }

        override fun onFinish(view: CountDownTextView?) {

        }
    }

    fun sendCode() {
        if (mStates.loginPhone.get().toString().isEmpty() || mStates.loginPhone.get()
                .toString().length != 10
        ) {
            TipDialog.show(ResUtil.getString(R.string.tv_phone_error_tip))
            return
        }
        mStates.errorTip.set("")

        WaitDialog.show(getString(R.string.loading))
        mPenileRequester.request(this@LoginActivity, mStates.loginPhone.get(), Const.MINUTEMAN)
    }

    open inner class ClickProxy {
        fun agreementChecked() {
            mStates.agreementChecked.get()?.let { mStates.agreementChecked.set(!it) }
        }

        fun goLogin() {
            if (!Utils.checkDebounce()) return
            if (mStates.agreementChecked.get() == false) {
                PopTip.show(getString(R.string.privacy_policy_tip)).iconError()
                return
            }
            if (mStates.verificationCodeState.get() == 1) {
                if (mStates.verificationCode.get().toString().isEmpty()) {
                    TipDialog.show(ResUtil.getString(R.string.tv_code_error_tip))
                    return
                }

                WaitDialog.show(getString(R.string.loading))
                mIsRegisterRequester.request(this@LoginActivity, mStates.loginPhone.get())
            } else {
                sendCode()
            }
        }

        fun userAgreement() {
            openUrlInWebView(mStates.url.get(), getString(R.string.user_agreement_empty))
        }

        fun agreement() {
            openUrlInWebView(mStates.url.get(), getString(R.string.privacy_policy))
        }

        fun acclaim() {
            if (!Utils.checkDebounce()) return
            mAcclaimXpop = AcclaimXpop(this@LoginActivity)
            XPopup.Builder(this@LoginActivity)
                .popupAnimation(data)
                .asCustom(mAcclaimXpop)
                .show()
        }

        fun contactService() {
            if (!Utils.checkDebounce()) return
            var customerBean = CustomerBean(
                "+86 13240445359",
                "13240445359@163.com",
                "13240445359",
                "13240445359@163.com"
            );
            mCustomerXpop = CustomerXpop(this@LoginActivity, customerBean)
            XPopup.Builder(this@LoginActivity)
                .popupAnimation(data)
                .asCustom(mCustomerXpop)
                .show()
        }

    }

    class LoginActivityStates : StateHolder() {
        val url: State<String> = State(Const.PRIVACY_URL)
        val privacyPolicy: State<String> = State(ResUtil.getString(R.string.privacy_policy))
        val userAgreement: State<String> = State(ResUtil.getString(R.string.user_agreement))
        var verificationCode: State<String> = State("")
        var verificationCodeState: State<Int> = State(0)
        var loginPhone: State<String> = State("")
        var agreementChecked: State<Boolean> = State(true)
        var clickableText: State<String> =
            State(ResUtil.getString(R.string.verification_message_code))
        var fullText: State<String> = State("")
        var errorTip: State<String> = State("")
    }


}